﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Keepo.Models;
using System.IO;
using System.Web;
using System.Net;
using Keepo.Helpers;

namespace Keepo.Helpers
{
    public class ImportHelper
    {
        public static DesignImage ImportImageFromUrl(string url)
        {
            string fileExt = Path.GetExtension(url);

            if(fileExt == null)
            {
                return null;
            }
            else
            {
                fileExt = fileExt.ToLower();
            }

            if (fileExt != ".jpg" && fileExt != ".png" && fileExt != ".gif")
            {
                return null;
            }

            DesignImage image = new DesignImage();
            image.ImageCategoryId = 1;
            image.Title = Path.GetFileNameWithoutExtension(url);

            string filname = Path.GetFileName(url);
            var relativePath = Path.Combine("resources/img/", filname);
            var rootedPath = HttpContext.Current.Server.MapPath(Path.Combine("~/", relativePath));
            image.URL = relativePath;

            byte[] data;
            using (WebClient client = new WebClient())
            {
                data = client.DownloadData(url);
            }

            try
            {
                File.WriteAllBytes(rootedPath, data);
            }
            catch { return null; }

            ImageHelper.addDesignImage(image);

            return image;
            
        }
    }
}
